import { TableColumnType } from "../../interface";
import { useEffect, useState } from "react";
import { gatewayAPI } from "../../apis/gateway";
import { Table, Tabs, Button, Space, Form, Input, DatePicker } from "antd";
import { Link, useHistory, useLocation, useRouteMatch } from "react-router-dom";
import ApiErrorMetrics from "./common/api-error-metrics";
import qs from "qs";
import { ReloadOutlined } from "@ant-design/icons";
import TableResizeBtn from "../../component/table-resize-btn";
import moment, { Moment } from "moment";
import { SizeType } from "antd/es/config-provider/SizeContext";

const {TabPane} = Tabs;
const {RangePicker} = DatePicker;

const ApiErrorPage = () => {
  const [tableData, setTableData] = useState([]);
  const [loading, setLoading] = useState(false)
  const [pager, setPager] = useState({
    pageIndex: 1,
    pageSize: 10,
    total: 0
  });
  const [metrics, setMetrics] = useState([]);
  const [searchData, setSearchData] = useState({
    searchKey: '',
    dateTime: [
      moment().subtract(1, 'd'),
      moment()
    ]
  });
  const [tableSize, setTableSize] = useState<SizeType>("middle");

  const h = useLocation();
  const history = useHistory();
  const query = qs.parse(h.search.substr(1));

  useEffect(() => {
    getTableData();
  }, [pager.pageIndex, searchData])

  useEffect(() => {
    getMetrics();
  }, [])

  function getTableData() {
    setLoading(true);
    const params = {
      pageIndex: pager.pageIndex,
      pageSize: pager.pageSize,
      searchKey: searchData.searchKey,
      sortDirection: "DESC",
      sort: "time",
    }
    if (searchData.dateTime && searchData.dateTime.length) {
      const setTime = (m: Moment) => {
        m.hour(0).minute(0).second(0);
        return m;
      }
      Object.assign(params, {
        end_time: setTime(searchData.dateTime[1]).unix() * 1000,
        start_time: setTime(searchData.dateTime[0]).unix() * 1000,
      })
    }
    gatewayAPI.errorGroup(params).then((res: any) => {
      if (res && res.success) {
        setTableData(res.data.list);
        setPager({
          ...pager,
          total: res.data.pageInfo.total
        })
      }
    }).finally(() => {
      setLoading(false);
    })
  }

  function getMetrics() {
    gatewayAPI.getErrorMetrics({}).then((res: any) => {
      if (res && res.success) {
        setMetrics(res.data)
      }
    })
  }

  function onTabChange(value: string) {
    history.replace(match.url + "?tab=" + value)
  }

  function onFinish(values: any) {
    setSearchData({
      dateTime: values.dateTime || [],
      searchKey: values.searchKey || '',
    })
  }

  const match = useRouteMatch();

  const columns: TableColumnType[] = [
    {
      title: '接口地址',
      dataIndex: 'url',
      key: 'url',
      width: '35%',
      ellipsis: true,
      render: (t: string, record: any) => {
        return (
          <Link to={ match.path + "/" + encodeURIComponent(record.url) }>
            { record.url }
          </Link>
        )
      }
    },
    {
      title: '最近发生时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: '20%'
    },
    {
      title: '最近状态码',
      dataIndex: 'http_code',
      key: 'http_code',
      width: '15%'
    },
    {
      title: '影响用户',
      dataIndex: 'user_count',
      key: 'user_count',
      width: '15%'
    },
    {
      title: '发生次数',
      dataIndex: 'count',
      key: 'count',
      width: '15%'
    }
  ]

  return (
    <div>
      <Tabs style={ {marginTop: -16} } onChange={onTabChange} defaultActiveKey={ query.tab as string || "metrics" }>
        <TabPane tab="异常走势" key="metrics">
          <ApiErrorMetrics metrics={ metrics }/>
        </TabPane>
        <TabPane tab="异常数据" key="list">
          <div style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between'
          } }>
            <Form
              name="basic"
              layout={ "inline" }
              labelCol={ {span: 0} }
              wrapperCol={ {span: 24} }
              initialValues={ searchData }
              onFinish={ onFinish }
            >
              <Form.Item name="searchKey">
                <Input placeholder={ "接口地址" } allowClear={ true } width={ 400 }/>
              </Form.Item>
              <Form.Item name={ "dateTime" }>
                <RangePicker
                  allowClear={ false }
                  defaultValue={ (searchData as any).dateTime }
                  style={ {marginBottom: 16} }
                />
              </Form.Item>
              <Form.Item>
                <Button htmlType={ "submit" } type={ "primary" }>查询</Button>
              </Form.Item>
            </Form>
            <Space size={ "middle" }>
              <a className="ui-hover-text" onClick={ e => e.preventDefault() }>
                <ReloadOutlined onClick={ getTableData }/>
              </a>
              <TableResizeBtn onChange={ setTableSize } defaultKey={ tableSize }/>
            </Space>
          </div>
          <Table
            rowKey={ "id" }
            bordered
            columns={ columns }
            loading={ loading }
            size={tableSize}
            dataSource={ tableData }
            pagination={ {
              showQuickJumper: false,
              showTotal: () => `共 ${ pager.total } 条`,
              pageSize: pager.pageSize,
              total: pager.total,
              current: pager.pageIndex,
              onChange: (v) => setPager({
                ...pager,
                pageIndex: v,
              })
            } }
          />
        </TabPane>
      </Tabs>
    </div>
  )
}

export default ApiErrorPage;